#-*-coding:utf-8-*-
from app.send_email import sent_email
from app.send_sms import send_sms
from app.db_models import *
from app.query_elec import query_elec_fun
import threading
import time
from sqlalchemy.orm import sessionmaker


def alter():
    """遍历已通知的用户，检查是否充值，对表记录进行修改"""
    print "alter function start!!!"
    all_rooms = Elec_Informed.query.all()  # 将表中的用户全部查出
    if all_rooms:
        recha_room = []  # 存放已充值的宿舍
        for i in all_rooms:  # 遍历每个宿舍
            result = query_elec_fun(i.room_num)
            if (result == "NoFound"):  # 不存在该宿舍
                print "NoFound:", i.room_num
            elif (result == "Timeout"):  # 查询超时
                print "Timeout", i.room_num
            else:
                remai = result["remaining_time"]
                if (remai == ">10"):  # 检查预计用电时间
                    i.recharge = "True"  # 已充值
                    db.session.commit()
                    recha_room.append(i.room_num)
                else:
                    if (int(remai) > 3):
                        i.recharge = "True"  # 已充值
                        db.session.commit()
                        recha_room.append(i.room_num)
                    else:
                        continue
        print "Sum of Recharged rooms:", len(recha_room)  # 输出已充值的宿舍

    else:
        print "Empty table"
    print "alter function done!!!"


def query():
    """遍历用户数据表，找出电量不足的宿舍"""
    print "query function start!!!"
    query_li = []  # 用于存放电量不足的寝室
    Session = sessionmaker()  # 创建session
    Session.configure(bind=db.engine)
    sess = Session()
    # 返回一个不重复的列表，列表的每一个元素是特殊的元组
    all_dom = sess.query(Elec_Users.room_num).distinct()
    sess.close()  # 关闭session
    for i in all_dom:  # 查询每一个宿舍
        each_dom_num = i[0]
        to_query = query_elec_fun(each_dom_num)
        if (to_query == "NoFound"):  # 不存在该宿舍
            print "NoFound:", i
        elif (to_query == "Timeout"):  # 查询超时
            print "Timeout:", i
        else:
            remaining_time = to_query.get('remaining_time')
            if remaining_time == ">10":
                continue
            else:
                if int(remaining_time) <= 3:  # 找到预计剩余时间小于等于三天的宿舍
                    query_li.append(each_dom_num)
                else:
                    pass

    print "Sum of Low-Level rooms:", len(query_li)  # 输出电量不足的宿舍
    print "query function done!!!"
    return query_li


def check():
    """将电量不足的宿舍与上次通知的宿舍比对，充值过的或者是第一次通知的宿舍将发送通知"""
    print "check function start!!!"
    need_info = query()  # 经查询需要通知的所有宿舍
    check_li = []  # 存放需要通知的宿舍
    for j in need_info:  # 遍历本次查询出电量不足的宿舍
        last_info = Elec_Informed.query.filter_by(
            room_num=j).first()  # 检查通知表中是否存在该宿舍
        if (last_info):
            if (last_info.recharge == "False"):  # 如果该宿舍未充值，则忽略
                continue
            else:  # 如果已充值的宿舍，则添加进通知列表check_li，并再次修改recharge为False
                last_info.recharge = "False"
                db.session.commit()
                check_li.append(j)
        else:  # 若不存在该宿舍，则添加到数据表及check_li中
            NewUser = Elec_Informed(room_num=j)
            db.session.add(NewUser)
            db.session.commit()
            check_li.append(j)
    print "Need to inform rooms:", check_li
    print "check function done!!!"
    return check_li


def send():
    """获得需要通知的宿舍后，发送通知"""
    send_li = check()
    if (send_li):
        sms_users = ""  # 用于存储需要短信通知的用户
        email_users = []  # 用于存储需要邮件通知的用户
        for num in send_li:
            Session = sessionmaker()  # 创建session
            Session.configure(bind=db.engine)
            sess = Session()
            users = sess.query(Elec_Users).filter_by(room_num=num).all()
            sess.close()  # 关闭session
            if users:
                for i in users:
                    if i.contact_way == "sms":
                        sms_users = (i.contact_info + ';' +
                                     sms_users)  # 用短信通知的用户
                    elif i.contact_way == "no":  # 无需通知的用户
                        continue
                    else:
                        email_users.append(i.contact_info)  # 邮件通知的用户
            else:
                continue
        if len(sms_users) > 0:
            send_sms(sms_users)
        else:
            pass
        if len(email_users) > 0:
            sent_email(email_users)
        else:
            pass

        print "Sms Users:", sms_users
        print "Email Users:", email_users
    else:
        print "No user need to inform"


def main():
    """负责调用以上各个任务函数"""
    print "Task start!!!"
    start = time.time()  # 任务开始时间
    alter()  # 执行检查宿舍是否充值的函数
    send()  # 执行send函数
    end = time.time()  # 任务结束时间
    used_time = round((end - start) / 60)  # 整个任务用时
    current = time.asctime(time.localtime(end))  # 获取格式化的时间
    Session = sessionmaker()  # 创建session
    Session.configure(bind=db.engine)
    sess = Session()
    count = sess.query(Elec_Users).count()  # 查询用户总数
    sms_info = sess.query(Elec_Users).filter_by(
        contact_way='sms').count()  # 查询使用短信通知的用户总数
    email_info = sess.query(Elec_Users).filter_by(
        contact_way='email').count()  # 查询使用邮箱通知的用户总数
    sess.close()  # 关闭session
    print "This task used: %s mins" % used_time
    print "Current time:", current
    print "The sum of all users is:", count
    print "The sum of Sms_Users:", sms_info
    print "The sum of Email_Users:", email_info
    print "All tasks done!!!"


def counter():
    """计数器函数，每隔一小时被定时器执行一次，计数器加1"""
    global times
    times = times + 1
    print "times = ", times
    if ((times % 12) == 0):  # 如果times能被12整除
        main()  # 执行main函数
    else:
        pass
    set_timer()


def set_timer():
    """定时器函数，每隔一小时执行一次counter函数"""
    print "set_timer start!!!"
    t = threading.Timer(3600, counter)
    t.start()

if __name__ == '__main__':
    times = 1  # 用于记录定时器执行的次数
    set_timer()
